package cn.gcjxsc.service.integral;

import cn.gcjxsc.common.consts.*;
import cn.gcjxsc.common.data.notify.redpack.RedPackResultData;
import cn.gcjxsc.common.util.validator.BindResult;
import cn.gcjxsc.consts.merchant.MerchantAccountType;
import cn.gcjxsc.data.redpack.MerRedPackData;
import cn.gcjxsc.data.redpack.RedPackRate;
import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.entity.member.integral.RedPackFlag;
import cn.gcjxsc.entity.merchant.Merchant;
import cn.gcjxsc.entity.merchant.MerchantAccount;
import cn.gcjxsc.entity.merchant.Store;
import cn.gcjxsc.entity.merchant.redpack.RedPackRecord;
import cn.gcjxsc.repository.member.integral.RedPackFlagRepository;
import cn.gcjxsc.service.merchant.MerchantAccountService;
import cn.gcjxsc.service.merchant.StoreSettingService;
import cn.gcjxsc.service.merchant.redpack.RedPackRecordService;
import com.zgxl.common.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 发送微信红包业务类.
 *
 * @author pumbaa
 * @since 1.0
 */
@Service
public class MemberWxRedPackService {
    @Autowired
    private MerchantAccountService accountService;
    @Autowired
    private RedPackRecordService recordService;
    @Autowired
    private StoreSettingService storeSettingService;
    @Autowired
    private RedPackFlagRepository flagRepository;

    public RedPackFlag findFlagBySnAndType(String sn, Integer type){
        return flagRepository.findBySnAndType(sn, type);
    }

    /**
     * 取得红包分配比例
     *
     * @return
     */
    public RedPackRate getRedPackRates() {
        RedPackRate rates = new RedPackRate();
        rates.setSendRate("0.45");
        rates.setShareRate("0.55");
        return rates;
    }

    public Map<String, String> findStoreSetting(Store store) {
        return storeSettingService.findCacheSetting(store.getId());
    }

    /**
     * 转换红包金额,单位:分.
     * 红包金额在[1-200]元区间
     * @param origAmount 计算得出的红包金额
     * @return 返回单位为分的红包金额
     */
    public BigDecimal processAmount(BigDecimal origAmount) {
        BigDecimal max = new BigDecimal("200");
        BigDecimal min = BigDecimal.ONE;
        if (origAmount.compareTo(max) > 0) {
            return max;
        } else if (origAmount.compareTo(min) < 0) {
            return min;
        }
        return origAmount;
    }

    public MerchantAccount findWxCashAccount(Merchant merchant) {
        return accountService.findByMerchantIdAndType(merchant, MerchantAccountType.WX_CASH.getType());
    }

    public RedPackRecord newRedPackRecord(MerRedPackData redPackData) {
        long timestamp = DateTimeUtil.getTimestamp();
        //商户流水
        RedPackRecord record = new RedPackRecord();
        record.setSourceSn(redPackData.getSn());
        record.setAmount(redPackData.getRedPackAmount());
        record.setCreated(timestamp);
        record.setOwnerId(redPackData.getMerchantId());
        record.setRemark(redPackData.getRemark());
        record.setType(redPackData.getType());
        record.setRate(redPackData.getRate());
        record.setTargetId(redPackData.getMemberId());
        record.setAmountRate(redPackData.getAmountRate());
        record.setStoreName(redPackData.getStoreName());
        record.setStoreId(redPackData.getStoreId());
        record.setStatus(RedPackStatus.PROCESSING.ordinal());
        record.setBaseAmount(redPackData.getBaseAmount());
        record.setTradeNo("");
        record.setDoneTime(0L);

        return record;
    }

    public RedPackRecord findBySnAndType(String sn, Integer type) {
        return recordService.findBySnAndType(sn, type);
    }

    /**
     * 发送红包
     * @param account 商户账户
     * @return
     */
    @Transactional
    public void processSendRedPack(MerchantAccount account, RedPackRecord record) {
        record.setAmount(record.getAmount().negate());
        account.setAmount(account.getAmount().add(record.getAmount()));

        RedPackFlag flag = new RedPackFlag();
        flag.setSn(record.getSourceSn());
        flag.setType(record.getType());

        flagRepository.save(flag);
        accountService.saveOrUpdate(account);
        recordService.saveOrUpdate(record);
    }



    @Transactional
    public void processRedPackFail(MerchantAccount account, RedPackRecord record, RedPackRecord backRecord){
        backRecord.setStatus(RedPackStatus.SUCCESS.ordinal());
        record.setStatus(RedPackStatus.FAIL.ordinal());

        account.setAmount(account.getAmount().add(backRecord.getAmount()));

        accountService.saveOrUpdate(account);
        recordService.saveOrUpdate(record, backRecord);
    }

    @Transactional
    public void processRedPackSuccess(RedPackRecord record, RedPackResultData data) {
        record.setStatus(RedPackStatus.SUCCESS.ordinal());
        record.setDoneTime(System.currentTimeMillis()/1000);
        record.setTradeNo(data.getTradeNo());

        recordService.saveOrUpdate(record);
    }

    /**
     * 检查订单是否为有效订单.<br>
     * 1.购物订单
     * 2.发货状态
     * 3.在线支付订单
     *
     * @param order      订单基本信息
     * @param bindResult 检验结果
     * @return 如果订单不符合状态, 返回false, 否则返回true
     */
    public boolean checkOrder(BaseOrder order, BindResult bindResult) {
        if (null == order) {
            bindResult.setErrorMsg("订单不能为空");
            return false;
        } else if (order.getDiscr() != OrderDiscr.SHOPPING_ORDER) {
            bindResult.setErrorMsg("非购物订单");
            return false;
        } else if (order.getPayStatus() != PayStatus.PAID) {
            bindResult.setErrorMsg("非[支付]状态订单");
            return false;
        } else if (order.getPayType() != PayType.ONLINE) {
            bindResult.setErrorMsg("非在线支付订单");
            return false;
        }
//        else if (order.getStatus() != OrderStatus.STATUS_SHIPPED) {
//            bindResult.setErrorMsg("非[发货]状态订单");
//            return false;
//        }
        return true;
    }
}
